//
//  KVTableHelper.swift
//  GerritHermes
//
//  Created by J.Zhou on 2020/2/10.
//  Copyright © 2020 周剑. All rights reserved.
//

import Foundation
import SQLite

final class KVTableHelper {
    static let shared = KVTableHelper()

    let db: Connection
    let encoder = JSONEncoder()
    let decoder = JSONDecoder()

    init() {
        let path = NSSearchPathForDirectoriesInDomains(
            .applicationSupportDirectory, .userDomainMask, true
        ).first! + "/" + Bundle.main.bundleIdentifier!

        // create parent directory iff it doesn’t exist
        do {
            try FileManager.default.createDirectory(
                atPath: path, withIntermediateDirectories: true, attributes: nil
            )

            db = try Connection("\(path)/db.sqlite3")
        } catch {
            db = try! Connection()
        }

//        db.trace {
//            Log.info($0)
//        }
    }
}

func <-(column: Expression<Blob?>, value: Data?) -> Setter {
    let blob = value.flatMap { Blob(bytes: [UInt8]($0)) }
    return column <- blob
}

func <-(column: Expression<Blob>, value: Data) -> Setter {
    return column <- Blob(bytes: [UInt8](value))
}

extension JSONDecoder {
    func decode<T>(_ type: T.Type, from blob: Blob) throws -> T where T : Decodable {
        try decode(type, from: Data(bytes: blob.bytes, count: blob.bytes.count))
    }
}


